//
// Created by user on 20-5-5.
//

#include "Timer.h"

unsigned long volatile jiffies = 0;

Timer timerListHead;

void timerInit() {

    Timer *tmp = NULL;

    // 1. 将jiffies清空
    jiffies = 0;

    // 2. 初始化定时器队列头
    initTimerList(&timerListHead, NULL, NULL, -1UL);

    // 3. 注册软中断处理函数，中断号为0
    registerSoftIRQ(0, &doTimer, NULL);

    // 4. 创建一个新的定时器，并加入到定时器队列中，测试定时器是否生效
    tmp = (Timer *) kmalloc(sizeof(Timer), 0);

    initTimerList(tmp, &testTimer, NULL, 5UL);

    addTimerList(tmp);

}

void doTimer(void *data) {

    Timer *tmp = containerOf(listNext(&timerListHead.list), Timer, list);

    while (!(listIsEmpty(&timerListHead.list)) && (tmp->expireJiffies <= jiffies)) {
        delTimerList(tmp);
        tmp->func(tmp->data);
        tmp = containerOf(listNext(&timerListHead.list), Timer, list);
    }

    printfColor(RED, WHITE, "(HPET: %ld)\n", jiffies);
}

void testTimer(void *data) {
    printfColor(BLUE, BLACK, "test_timer");
}


void initTimerList(Timer *timer, void (*func)(void *data), void *data, unsigned long expireJiffies) {
    listInit(&timer->list);
    timer->func = func;
    timer->data = data;
    timer->expireJiffies = jiffies + expireJiffies;
}

void addTimerList(Timer *timer) {

    // 1. 从定时功能队列头获取到下一个定时功能
    Timer *tmp = containerOf(listNext(&timerListHead.list),
                             Timer, list);

    // 2. 判断定时功能队列头是否不止一个
    // 如果是就执行内部循环找到定时功能队列中正好大于要添加的定时功能
    if (listIsEmpty(&timerListHead.list)) {

        while (tmp->expireJiffies < timer->expireJiffies)
            tmp = containerOf(listNext(&tmp->list),
                              Timer, list);

    }

    // 3. 添加定时功能到定时功能队列
    listAddToBehind(&tmp->list, &timer->list);
}

void delTimerList(Timer *timer) {
    listDel(&timer->list);
}
